<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Users;
use App\Models\Linkslists;
use App\Models\Memberorders;
use App\Models\Apparticles;
use App\Models\Linkslistsimages;
use App\Models\Smslists;
use App\Models\Worklink;
use App\Services\WechatService;
use App\Services\WXServices;
use App\Services\CommonService;
use App\Services\ThirdsmsService;
use App\Services\WechattmplmsgService;
use App\Services\OutputService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;
use App\Jobs\Htmlosshanndle;
use App\Jobs\Wxkfhanndle;
use MarkdownEditor,Log,Pay,Response;

class UsersController extends Controller
{
    public function userRefresh(Request $request)
    {
        $users = Users::getUsersById($request->users_id);
        $users_id   = encrypt($users->id);
        $users = $users->toArray();
        unset($users['id']);
        $users['users_id'] = $users_id;
        return response()->json(['status' => 'success', 'msg' => '已加载最新数据', 'users' => $users]);
    }

    public function aboutLists(Request $request)
    {
        $abouts = Apparticles::articleLists(3);
        return response()->json(['status' => 'success', 'msg' => '已加载最新数据', 'data' => $abouts]);
    }

    public function aboutDetial(Request $request)
    {
        $aboutinfo = Apparticles::articleDetial($request->id);
        if (empty($aboutinfo)) return response()->json(['status' => 'error', 'msg' => '文章不存在！']);
        $aboutinfo->msg = MarkdownEditor::parse($aboutinfo->msg);
        return response()->json(['status' => 'success', 'msg' => '已加载最新数据', 'data' => $aboutinfo]);
    }

    public function password(Request $request)
    {
        $wechat_openid = WXServices::login($request->code);
        if ($wechat_openid == "Error") return response()->json(['status' => 'error', 'msg' => '获取失败,请联系客服处理！']);
        $username  = WXServices::getPhone($request->encryptedData, $request->iv, $wechat_openid);
        if(!preg_match("/^1[23456789]{1}\d{9}$/",$username)) return response()->json(['status' => 'error', 'msg' => '获取失败,请联系客服处理！']);
        $users_id = $request->users_id;
        $users = Users::getAdminByUsername($username);
        if (!empty($users) && $users_id != $users->id) return response()->json(['status' => 'error', 'msg' => '账户已存在,无法重新添加！']);
        $password_uncode = $users_id.rand(10000,99999);
        $password = Hash::make($password_uncode);
        Users::apiUpdateUsersPassword($users_id,$username,$password);
        return response()->json(['status' => 'success', 'msg' => '密码更新成功！','data'=>['url'=>'https://bab.moreqifu.cn/admin/login','username'=>$username,'password'=>$password_uncode]]);
    }

    public function alipayCallBack(Request $request)
    {
        $alipay = Pay::alipay(config('pay.alipay'));
        $data = $alipay->verify(); // 是的，验签就这么简单！
        if ($request->trade_status != 'TRADE_SUCCESS') return '支付失败';
        $order = Memberorders::getByOrderNo($request->out_trade_no);
        if (empty($order)) return '订单不存在';
        if ($order->pay_status == 3) return '已支付';
        if ($order->price != $request->total_amount) return '金额不一样';
        // 修改订单状态
        Memberorders::updatePayStatus($request->out_trade_no, [
            'pay_status'    => 3,
            'transaction_id'=> $request->trade_no,
            'type'          => 2,
        ]);
        if ($order->product_id == 2) {
            $limit_pv = 50000;
            $limit_status = 1;
        } elseif ($order->product_id == 3) {
            $limit_pv = 500000;
            $limit_status = 1;
        } elseif ($order->product_id == 4) {
            $limit_pv = 1000000;
            $limit_status = 2;
        } else {
            $limit_pv = 100;
            $limit_status = 1;
        }
        // 把全部订单改为可用
        Linkslists::updateLinksListsStatus($order->users_id,$limit_status,$limit_pv,$order->end_time);
        Worklink::updateWorkLinkMember($order->users_id,$limit_pv,$order->end_time);
        Users::updateUsersMemberTime($order->users_id,$order->product_id,$order->end_time);
        // 更新线上OSS
        Htmlosshanndle::dispatch($order->users_id,"","")->delay(10);
        Wxkfhanndle::dispatch($order->users_id)->delay(10);
        // 会员开通公众号推送
        $users = Users::getUsersWechatOpenid($order->users_id);
        WechattmplmsgService::sendMemberTempleteMsg($users->wechat_openid,$users->username,$order->product_id,date("Y-m-d H:i:s",$order->start_time),date("Y-m-d H:i:s",$order->end_time));
        return $alipay->success();
    }

    public function sendMsn(Request $request)
    {
        if (empty($request->phone)) return Response::json(["status"=>"error","code"=>"1001","msg"=>"请输入电话号码！"]);
        $sign = CommonService::aesDncrypt($request->sign);
        if ($sign != 'wl'.$request->time.'lw') return Response::json(["status"=>"error","code"=>"1004","msg"=>"接口异常,请稍后重试！"]);
        if (time()-$request->time >= 600) return Response::json(["status"=>"error","code"=>"1004","msg"=>"请刷新网页重新获取验证码!"]);
        $phone = str_replace(" ","",$request->phone);
        $msncode = Redis::get("register".$phone);
        $code = rand(1000,9999);
        if (!empty($msncode)) {
            $msninfo = json_decode($msncode);
            $difftime = time()-$msninfo->time;
            if ($difftime <= 60) return Response::json(["status"=>"error","code"=>"1004","msg"=>"请在".(60-$difftime)."秒后重新获取密码！"]);
        }
        // 获取短信发送次数
        $msnTimes = Redis::get("msn_times_".$phone);
        // 是否需要图形验证码
        $need_captcha = 1;
        if (empty($msnTimes)) {
            // 首次发送保存10分钟
            Redis::setex("msn_times_".$phone,600,1);
        } else {
            if ($msnTimes >= 5) return OutputService::error("短信发送频繁,请30分钟后尝试！");
            if ($msnTimes >= 2) {
                $need_captcha = 2;
            }
            Redis::incr("msn_times_".$phone) ;
        }
        $templateParam = json_encode(["code"=>$code]);
        $sendstatus = ThirdsmsService::alibabaSendSms($phone,$templateParam);
        if ($sendstatus["status"] == "success") {
            // 发送成功后才保存验证码
            Redis::setex("register".$phone,300, json_encode(["code"=>$code,"time"=>time()]));
            $message = "验证码为：".$code."，您正在注册成为平台会员，感谢您的支持！";
            Smslists::insertRegisterSms($phone,$message,1);
            return Response::json(["status"=>"success","code"=>"1000","msg"=>"验证码发送成功，5分钟内有效！","need_captcha"=>$need_captcha]);
        } else {
            return Response::json(["status"=>"error","code"=>"1005","msg"=>$sendstatus["message"]]);
        }
    }

}
